//
//  HMStatusViewModel.swift
//  Black22
//
//  Created by Apple on 16/11/23.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import YYText

//  对应的视图是首页的cell
class HMStatusViewModel: NSObject {
    
    //  处理首页内存转发富文本的操作
    func handleHomeAttributedString(content: String) -> NSAttributedString {
        
        //  微博内容转出富文本
        let resultAttributedStr = NSMutableAttributedString(string: content)
        //  使用正则表达式匹配表情描述字符串
        let matchResult = try! NSRegularExpression(pattern: "\\[\\w+\\]", options: []).matches(in: content, options: [], range: NSMakeRange(0, (content as NSString).length))
        //  遍历匹配结果获取对应的表情描述字符串, 匹配结果翻转倒着替换表情富文本
        for match in matchResult.reversed() {
            //  表情描述字符串匹配的范围
            let range = match.range
            //  表情描述字符串
            let chs = (content as NSString).substring(with: range)
            //  根据表情描述字符串查找对应的表情模型
            if let emoticon = HMEmoticonTools.sharedTools.selectEmoticon(chs: chs) {
                //  表情模型找到了，把表情模型的对应的图片名生成一个富文本
                let image = UIImage(named: emoticon.fullPath!)!
                //  使用YYText里面的方法创建富文本
                let emoticonAttributedStr = NSAttributedString.yy_attachmentString(withEmojiImage: image, fontSize: 14)!
                
                
                //  根据模型生富文本
//                let emoticonAttributedStr = NSAttributedString.attributedStringWithEmoticon(emoticon: emoticon, font: UIFont.systemFont(ofSize: 14))
                
                
                //  替换表情描述范围的富文本
                resultAttributedStr.replaceCharacters(in: range, with: emoticonAttributedStr)
                
            }
            
        }
        //  设置富文本字体大小
        resultAttributedStr.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, resultAttributedStr.length))
        
        //  添加高亮 @
        addHighlitedAttributedString(resultAttributedStr: resultAttributedStr, patten: "@[^:]+")
        //  话题 ##
        addHighlitedAttributedString(resultAttributedStr: resultAttributedStr, patten: "#[^#]+#")
        //  链接
        addHighlitedAttributedString(resultAttributedStr: resultAttributedStr, patten: "http[s]?://[^\\s\\u4e00-\\u9fa5]+")
        
        
        return resultAttributedStr
    }
    
    //  添加高亮
    private func addHighlitedAttributedString(resultAttributedStr: NSMutableAttributedString, patten: String) {
        //  添加高亮
        let text = resultAttributedStr.string
        //  匹配高亮结果
        let matchHighlightedResult = try! NSRegularExpression(pattern: patten, options: []).matches(in: text, options: [], range: NSMakeRange(0, (text as NSString).length))
        for matchHighlighted in matchHighlightedResult {
            //  匹配高亮的范围
            let matchHighlightedRange = matchHighlighted.range
            
            //  设置富文本前景颜色
            resultAttributedStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: matchHighlightedRange)
            
            let textHighlight = YYTextHighlight()
            let bgColor = UIColor.red
            //  设置选中背景
            let textBorder = YYTextBorder(fill: bgColor, cornerRadius: 3)
            textBorder.insets = UIEdgeInsets(top: 1, left: 0, bottom: 0, right: 0)
            textHighlight.setBackgroundBorder(textBorder)
            //  设置高亮
            resultAttributedStr.yy_setTextHighlight(textHighlight, range: matchHighlightedRange)
            
        }
    }
    
    
    //  微博模型
    var status: HMStatus? {
        didSet {
            guard let currentStatus = status else {
                return
            }
            //
            retweetContent = handleRetweetContent(status: currentStatus)
            verfiedTypeImage = handleVerfiedTypeImage(verfiedType: currentStatus.user?.verified_type ?? 0)
            memberImage = handleMBrankImage(mbrank: currentStatus.user?.mbrank ?? 0)
            retweetCountString = handleCountString(count: currentStatus.reposts_count, defaultTitle: "转发")
            commentCountString = handleCountString(count: currentStatus.comments_count, defaultTitle: "评论")
            unLikeCountString = handleCountString(count: currentStatus.attitudes_count, defaultTitle: "赞")
            sourceContent = handleSourceContent(source: status?.source ?? "")
            originalAttributedStr = handleHomeAttributedString(content: currentStatus.text!)
            if retweetContent != nil {
                retweetAttributedStr = handleHomeAttributedString(content: retweetContent!)
            }
            
        }
    }
    //  原创微博富文本内容
    var originalAttributedStr: NSAttributedString?
    //  转发微博富文本内容
    var retweetAttributedStr: NSAttributedString?
    //  转发微博内容
    var retweetContent: String?
    //  认证类型图片
    var verfiedTypeImage: UIImage?
    //  会员等级图片
    var memberImage: UIImage?
    //  转发数
    var retweetCountString: String?
    //  评论数
    var commentCountString: String?
    //  赞
    var unLikeCountString: String?
    
    //  来源
    var sourceContent: String?
    
    //  时间来源
    /*
        1. 判断是否是今年
            -判断是否是今天
                判断是否是1分钟前
                    -刚刚
                判断是否是1小时之前
                    -xx分钟前
                其它
                    -xx小时前
            -判断是否是昨天
                昨天 10:10
            -其它
                11-24 10:10
        2. 不是今年
            - 2015-10-10 20:20
    */
    var timeString: String? {
        //  判断发微博日期是否为nil
        guard let createDate = status?.created_at else {
            return nil
        }
        
        let dt = DateFormatter()
        dt.locale = Locale(identifier: "en_US")
        
        if isThisYear(createAtDate: createDate) {
            //  今年
            let calendar = Calendar.current
            if calendar.isDateInToday(createDate) {
                //  今天
                let timeInterval = abs(createDate.timeIntervalSinceNow)
                if timeInterval < 60 {
                    return "刚刚"
                } else if timeInterval < 3600 {
                    let result = Int(timeInterval) / 60
                    return "\(result)分钟前"
                } else {
                    let result = Int(timeInterval) / 3600
                    return "\(result)小时前"
                }
                
                
            } else if calendar.isDateInYesterday(createDate) {
                //  昨天
                dt.dateFormat = "昨天 HH:mm"
            } else {
                //  其它
                dt.dateFormat = "MM-dd HH:mm"
            }
            
        } else {
            //  不是今年
            dt.dateFormat = "yyyy-MM-dd HH:mm"
        }
        return dt.string(from: createDate)
        
        
    }
    //  判断是否是今年
    fileprivate func isThisYear(createAtDate: Date) -> Bool {
    
        let dt = DateFormatter()
        dt.locale = Locale(identifier: "en_US")
        dt.dateFormat = "yyyy"
        let createDateYear = dt.string(from: createAtDate)
        
        let currentDateYear = dt.string(from: Date())
        return createDateYear == currentDateYear
    }
    
    
    //  处理来源数据
    fileprivate func handleSourceContent(source: String) -> String? {
        
        if let startRange = source.range(of: "\">"), let endRange = source.range(of: "</") {
            //  获取最后的光标位置
            let startIndex = startRange.upperBound
            //  获取开始光标位置
            let endIndex = endRange.lowerBound
            
            let content = "来自: " + source.substring(with: startIndex..<endIndex)
            return content
            
        }
        return nil
    }
    
    
    //  处理转发数评论数赞数
    fileprivate func handleCountString(count: Int, defaultTitle: String) -> String {
        if count > 0 {
            return "\(count)"
        }
        
        return defaultTitle
    }
    
    
    
    //  处理会员等级图片
    func handleMBrankImage(mbrank: Int) -> UIImage? {
        if mbrank >= 1 && mbrank <= 6 {
            return UIImage(named: "common_icon_membership_level\(mbrank)")
        }
        return nil
    }
    
    //  处理认证类型图片
    func handleVerfiedTypeImage(verfiedType: Int) -> UIImage? {
        switch verfiedType {
        case 1:
            return UIImage(named: "avatar_vip")
        case 2, 3, 5:
            return UIImage(named: "avatar_enterprise_vip")
        case 220:
            return UIImage(named: "avatar_grassroot")
        default:
            return nil
        }
    }
    
    //  处理转发微博内容
    func handleRetweetContent(status: HMStatus) -> String? {
        
        if status.retweeted_status != nil {
            if let name = status.retweeted_status?.user?.screen_name, let content = status.retweeted_status?.text {
                return "@" + name + ": " + content
            }
        }
        return nil
    }
    
}
